package com.lyx.bluetoothdemo

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.location.LocationManager
import android.util.Log

object BluetoothHelper {

    var bleContext: Context? = null
    var bluetoothAdapter: BluetoothAdapter? = null

    fun bluetoothAdapterInit(context: Context): BluetoothInitResult {
        bleContext = context
        if (bluetoothAdapter == null) bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        return when {
            bluetoothAdapter == null -> BluetoothNull
            !isLocServiceEnable(context) -> BluetoothPermission
            !getBluetoothAdapterState() -> BluetoothNotOpen
            else -> BluetoothSuccess
        }
    }

    private fun getBluetoothAdapterState(): Boolean {
        return bluetoothAdapter?.isEnabled ?: false
    }

    private fun isLocServiceEnable(context: Context): Boolean {
        val locationManager =
            context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val gps: Boolean = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        val network: Boolean =
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        return gps || network
    }

    /**
     * 查询已配对设备
     */
    fun getBondedDevices(): List<BluetoothModel> {
        Log.d("lyx", "---------------------------------------------")
        var bondedDevices = mutableListOf<BluetoothModel>()
        val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices
        pairedDevices?.forEach { device ->
            Log.d("lyx", "蓝牙名：" + device.name + "    蓝牙MAC：" + device.address)
            bondedDevices.add(BluetoothModel(device.name, device.address))
        }
        return bondedDevices
    }

    /**
     * 打开蓝牙
     */
    fun openBluetoothSetting() {
        bluetoothAdapter?.enable()
    }

    fun closeBluetoothAdapter() {
        bluetoothAdapter?.disable()
    }

}